import { defineStore } from 'pinia'
import type { Product, CartItem } from '../types'

interface CartState {
  items: CartItem[]
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    items: []
  }),
  
  getters: {
    totalItems(): number {
      return this.items.length
    },
    
    totalAmount(): number {
      return this.items.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    }
  },
  
  actions: {
    addToCart(product: Product): void {
      const existingItem = this.items.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.items.push({ ...product, quantity: 1 })
      }
    },
    
    removeFromCart(productId: number): void {
      const index = this.items.findIndex(item => item.id === productId)
      if (index > -1) {
        this.items.splice(index, 1)
      }
    },
    
    updateQuantity(productId: number, quantity: number): void {
      const item = this.items.find(item => item.id === productId)
      if (item && quantity > 0) {
        item.quantity = quantity
      }
    }
  }
}) 